package com.gjun.struts.resource.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gjun.struts.bean.ext.Item;
import com.gjun.struts.bean.ext.Order;
import com.gjun.struts.resource.dao.IItemDao;

public class ItemDaoImpl extends HibernateDaoSupport implements IItemDao {

	public void saveItem(Item item, Order order) {
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		session.beginTransaction();
		item.setOrder(order);
		session.save(item);
		session.getTransaction().commit();
		session.close();
	}

	public List<Item> getItemByOrderId(int orderId) {
		// TODO Auto-generated method stub
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		String hql = "select i from Item i where i.order.id=?";
		
		List<Item> items = session.createQuery(hql).setParameter(0, orderId).list();
		session.close();
		return items;
	
	}

	public List<Item> getItemByOrderId(int orderId, int start, int pageSize) {
		// TODO Auto-generated method stub
		Session session = this.getHibernateTemplate().getSessionFactory().openSession();
		String hql = "select i from Item i where i.order.id=?";
		Query query = session.createQuery(hql);
		query.setMaxResults(pageSize);
		query.setFirstResult(start);
		List<Item> items = query.setParameter(0, orderId).list();
		session.close();
		return items;
	}

	public void deleteItemById(Item item) {
		this.getHibernateTemplate().delete(item);
		
	}

	public Item getItemById(int id) {
		// TODO Auto-generated method stub
		return (Item)this.getHibernateTemplate().get(Item.class, id);
	}

	public void updateItem(Item item) {
		// TODO Auto-generated method stub
		this.getHibernateTemplate().update(item);
		
	}

}
